package com.qutan.app.core.manager;

import com.alibaba.dubbo.config.annotation.Service;
import com.i7time.entity.User;
import com.i7time.service.UserService;
import com.qutan.app.core.cache.UserCache;
import com.qutan.app.core.domain.UserInfo;
import com.qutan.app.core.domain.enumclass.SexType;
import com.qutan.app.core.domain.enumclass.ThreeLogin;
import com.qutan.app.core.repository.UserInfoRepository;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Date;
import java.time.Instant;
import java.util.List;
import java.util.Map;


/**
 * Created by pengweiyuan on 6/4/16.
 */
@Service(version = "1.0.0",interfaceClass = UserService.class)
public class UserManager implements UserService {

    private static Logger log = org.slf4j.LoggerFactory.getLogger(UserManager.class);

    /**
     * 商家注册默认密码
     */
    private static final String DEFAULT_PWD= DigestUtils.md5Hex("123456");


    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private UserCache userCache;

    @Override
    public boolean isExist(String tel) {
        UserInfo userByTel = userCache.getUserByTel(tel);
        if(userByTel!=null)return true;
        List<UserInfo> userInfos = userInfoRepository.findByTel(tel);
        return !userInfos.isEmpty();
    }

    @Override
    public User getUserByTel(String tel) {
        UserInfo userInfo = userCache.getUserByTel(tel);
        if(userInfo==null) {
            List<UserInfo> userInfos = userInfoRepository.findByTel(tel);
            if (userInfos.isEmpty()) return null;
            if (userInfos.size() > 1) {
                log.warn("userInfos size >1 tel={}", tel);
            }
            userInfo=userInfos.get(0);
            userCache.update(userInfo);
            userCache.addTelIDKey(userInfo.getId().toString(),userInfo.getTel());
        }
        //检测内存,如果存在,把内存最新的内容返回
        UserInfo userCacheById = userCache.getById(userInfo.getId());
        if(userCacheById!=null) {
            userCache.update(userCacheById);//延长过期时间
            return userCacheById.converInfo2User();
        }else{
            return userInfo.converInfo2User();
        }
    }

    @Override
    public User register(String tel, String password, String nick_name, String avatar, String sex, String birthday) {
        try {
            UserInfo userInfo = new UserInfo();
            userInfo.setTel(tel);
            userInfo.setPassword(password);
            Long passwordTimestamp = Date.from(Instant.now()).getTime();
            userInfo.setPasswordTimestamp(passwordTimestamp);
            userInfo.setNick_name(nick_name);
            userInfo.setAvatar(avatar);
            SexType sexType = SexType.getSexTypeByFlag(Integer.parseInt(sex));
            userInfo.setSex(sexType);
            userInfo.setBirthday(birthday);
            UserInfo save = userInfoRepository.save(userInfo);
            return save.converInfo2User();
        } catch (Exception e) {
            log.error("register error,tel=" + tel + " password=" + password + " error,", e);
            return null;
        }
    }

    @Override
    public User addUserDetail(long id, String nick_name, String avatar, String sex, String birthday) {
        try {
            UserInfo userInfo = userInfoRepository.findOne(id);
            if (userInfo == null) {
                log.warn("addUserDetail userInfo is not exit id={}", id);
                return null;
            }
            userInfo.setBirthday(birthday);
            userInfo.setNick_name(nick_name);
            userInfo.setAvatar(avatar);
            SexType sexType = SexType.getSexTypeByFlag(Integer.parseInt(sex));
            userInfo.setSex(sexType);
            userCache.update(userInfo);
            return  userInfoRepository.save(userInfo).converInfo2User();
        } catch (Exception ex) {
            log.error("addUserDetail userid={} error", id, ex);
        }
        return null;
    }

    /**
     * @param id
     * @param newPwd
     * @return int 0.系统错误  1.成功，2.原密码不匹配
     */
    @Override
    public boolean resetPassword(long id, String newPwd) {
        try{
            UserInfo userInfo=userInfoRepository.findOne(id);
            if(userInfo==null)return  false;
            userInfo.setPassword(newPwd);
            userInfoRepository.save(userInfo);
            userCache.update(userInfo);
            return true;
        }catch (Exception e){
            log.error("resetPassword error userId={}",id,e);
            return  false;
        }
    }

    @Override
    public User getUserById(long id) {
        UserInfo userInfo=userCache.getById(id);
        if(userInfo==null){
            userInfo= userInfoRepository.getOne(id);
            userCache.update(userInfo);
        }
        if(userInfo==null)return null;
        return userInfo.converInfo2User();
    }

    @Override
    public User modifyUser(long id, Map<String, Object> propertyMap) {
        return null;
    }

    @Override
    public boolean uploadUserPic(long id, String imgUrl) {
        UserInfo userInfo = userInfoRepository.findOne(id);
        userInfo.setAvatar(imgUrl);
        userInfoRepository.save(userInfo);
        userCache.update(userInfo);
        return false;
    }

    /**
     * 第三方登陆
     * @param openid
     * @param thirdLoginType
     * @param nickname
     * @param sex
     * @param avatar
     * @return
     */
    @Override
    public User thirdLogin(String openid, String thirdLoginType, String nickname, String sex, String avatar) {
        UserInfo userInfo=userInfoRepository.findByOpenId(openid);
        if(userInfo!=null){
            UserInfo byId = userCache.getById(userInfo.getId());
            if(byId!=null)return byId.converInfo2User();
            else userInfo.converInfo2User();
        }
        userInfo =new UserInfo();
        userInfo.setOpenId(openid);
        ThreeLogin threeLoginByFlag = ThreeLogin.getThreeLoginByFlag(Integer.parseInt(thirdLoginType));
        userInfo.setIsThirdLogin(threeLoginByFlag);
        userInfo.setNick_name(nickname);
        SexType sexType=SexType.getSexTypeByFlag(Integer.parseInt(sex));
        userInfo.setSex(sexType);
        userInfo.setAvatar(avatar);
        UserInfo userInfoResult = userInfoRepository.save(userInfo);
        userCache.update(userInfoResult);
        return userInfoResult.converInfo2User();
    }

    @Override
    public User getUserByOpenid(String openid) {
        return null;
    }


    /**
     * 商家注册场景的时候 注册默认的User的账号
     * @param tel
     * @param nick_name
     * @param avatar
     * @return
     */
    public User registerSceneUser(String tel, String nick_name, String avatar){
        return  register(tel,DEFAULT_PWD,nick_name,avatar,String.valueOf(SexType.FEMALE.getSort()),"");
    }
}
